package cn.tedu.loding.service.impl;


import cn.tedu.loding.ex.ServiceException;
import cn.tedu.loding.mapper.BannerMapper;
import cn.tedu.loding.pojo.dto.BannerAddNewDTO;
import cn.tedu.loding.pojo.entity.Banner;
import cn.tedu.loding.pojo.vo.BannerListItemVO;
import cn.tedu.loding.pojo.vo.BannerStandardVO;
import cn.tedu.loding.service.IBannerService;
import cn.tedu.loding.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@Transactional
public class BannerServiceImpl implements IBannerService {

    @Autowired
    BannerMapper bannerMapper;

    public void addNew(BannerAddNewDTO bannerAddNewDTO){
        String url = bannerAddNewDTO.getUrl();
        int count = bannerMapper.countByUrl(url);
        if (count !=0){
            String message = "添加轮播图失败，尝试添加的轮播图url已经被占用！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        Banner banner = new Banner();
        BeanUtils.copyProperties(bannerAddNewDTO,banner);
        log.debug("即将插入轮播图数据：{}",banner);
        int rows=bannerMapper.insert(banner);
        if (rows!=1){
            String message = "添加轮播图失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public List<BannerListItemVO> list() {
        return bannerMapper.list();
    }

    @Override
    public void delete(Long id){
        log.debug("开始处理【删除轮播图】的请求，参数={}",id);
        BannerStandardVO queryResult = bannerMapper.getStandardById(id);
        if (queryResult == null){
            String message = "删除轮播图,轮播图url已经被占用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        log.debug("即将删除轮播图数据...");
        bannerMapper.deleteById(id);
        log.debug("删除轮播图，完成！");
    }
}
